﻿using MySSO.Core.Entity;
using MySSO.Core.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MySSO.Core.Service
{
    public class IPService
    {
        private readonly IPCityRepository _iPCityRepository;
        public IPService()
        {
            _iPCityRepository = new IPCityRepository();
        }
        public IPCityEntity GetIPCityByIp(string ip)
        {
            long ipvalue = IpToLong(ip);
            return GetIPCityByIpValue(ipvalue);
        }

        public string GetCityByIp(string ip)
        {
            long ipvalue = IpToLong(ip);
            var entity = this.GetIPCityByIpValue(ipvalue);
            if (entity == null)
            {
                return "";
            }
            else
            {
                return entity.IP_City;
            }
        }

        public IPCityEntity GetIPCityByIpValue(long ipValue)
        {
            return _iPCityRepository.GetIPCityByIpValue(ipValue);
        }

        private long IpToLong(string ip)
        {
            try
            {
                string[] cip = ip.Trim().Split('.');
                if (cip.Length != 4)
                    return 0;
                string[] aip = new string[4];
                cip.CopyTo(aip, 0);
                if (cip.Length < 3)
                {
                    for (int i = 3; i > cip.Length; i--)
                    {
                        aip[i] = "0";
                    }
                }
                uint[] iip = new uint[4];
                Regex reg = new Regex(@"\d+");
                for (int x = 0; x < aip.Length; x++)
                {
                    if (reg.IsMatch(aip[x]))
                        iip[x] = Convert.ToUInt32(aip[x]);
                    else
                        iip[x] = 0;
                }
                long uip = Convert.ToInt64(256 * 256 * 256 * iip[0] + 256 * 256 * iip[1] + 256 * iip[2] + iip[3]);
                return uip;
            }
            catch (Exception ess)
            {
                throw ess;
            }
        }
    }
}
